;
(function() {
	//定義小球
	function Vec2(x, y) {
		this.x = x || 0;
		this.y = y || 0;
	}
	Vec2.prototype = {
		add: function(v) {
			this.x += v.x;
			this.y += v.y;
		},
		clone:function(){
			return new Vec2(this.x,this.y);
		}
	}

	function Ball(pos, size) {
		this.pos = pos || new Vec2();
		this.size = size || new Vec2(20, 20);
		this.sp = new Vec2();
		this.$el = $("<div>").
			addClass('ball')
			.width(this.size.x)
			.height(this.size.y)
			.css('top',this.pos.y+'px')
			.css('left',this.pos.x+'px');
		$("#wrapper").append(this.$el);
	}

	Ball.prototype = {
		update: function() {
			this.sp.y += g;
			var sp=this.sp.clone();
			var offsetY=0;
			sp.x=keyPress[keyMap.left]?-3:keyPress[keyMap.right]?3:0;
			if(this.pos.y<=100&&this.sp.y<0){
				sp.y=0;
				offsetY=this.sp.y;
				console.log("kk");
			}
			this.pos.add(sp);
			this.$el.css("top", this.pos.y + "px");
			this.$el.css("left", this.pos.x + "px");
			return offsetY;
		}
	}

	function Platform(pos, size) {
		this.pos = pos || new Vec2(20, 40);
		this.size = size || new Vec2(50, 10);
		this.$el = $('<div>')
			.addClass('platform')
			.width(this.size.x)
			.height(this.size.y)
			.css('top',this.pos.y+'px')
			.css('left',this.pos.x+'px');
		$("#wrapper").append(this.$el);
	}

	Platform.prototype = {
		update: function(offsetY) {
			this.pos.y-=offsetY;
			this.$el.css("top", this.pos.y + "px");
			this.$el.css("left", this.pos.x + "px");
		}
	}

	var g = 0.9,
		w = 240,
		h = 300,
		spacing = 50;
	$("#wrapper").width(w).height(h);
	var ball = new Ball(new Vec2(110, 100));
	var platforms = [];

	var Timer = setInterval(run, 1000 / 30);

	function run() {
		update();
		collisionCheck();

	}

	function update() {
		var offsetY=ball.update();
		for (var i = 0; i < platforms.length; i++) {
			platforms[i].update(offsetY);
			if (platforms[i].pos.y > h) {
				platforms.splice(i, 1);
			}
		}
		var lastPlatformH=h;
		if(platforms.length>0){
			lastPlatformH=platforms[platforms.length-1].pos.y;
		}
		if(lastPlatformH>spacing){
			var x=~~(Math.random()*(w-50));
			platforms.push(new Platform(new Vec2(x,lastPlatformH-spacing)));
		}
	}

	function collisionCheck() {
		for (var i = 0; i < platforms.length; i++) {
			var platform = platforms[i];
			if (ball.pos.x + ball.size.x >= platform.pos.x
            	&& ball.pos.x <= platform.pos.x + platform.size.x
            	&& ball.pos.y + ball.size.y >= platform.pos.y
            	&& ball.pos.y <= platform.pos.y + platform.size.y
				&& ball.sp.y >= 0) {
				ball.sp.y = -14;
			}
		}
	}
	
	var keyPress=[];
	var keyMap={
		left:37,
		right:39
	};
	$(document).on('keydown',function(event){
		keyPress[event.keyCode]=true;
	}).on('keyup',function(event){
		keyPress[event.keyCode]=false;
	});
})($);